import { ipcMain } from "electron";
import fs from "node:fs";
import fsp from "node:fs/promises";
import { readFileAllLines } from "@elec/main/util/file-utils.ts";

(() => {
  /**
   * 读取ini文件
   */
  ipcMain.handle("config.readIni", async (_, file: string, section?: string, key?: string) => {
    try {
      if (!fs.existsSync(file)) return null;
      const content = await fsp.readFile(file, { encoding: "utf-8" });
      const ini = await import("ini");
      const config: Record<string, Record<string, string>> = ini.parse(content);
      let result: any = config;
      if (section) {
        result = config[section];
      }
      if (key) {
        result = result[key];
      }
      return result;
    } catch (e) {
      console.error("[config-file] read ini file error", file, e);
      return null;
    }
  });

  /**
   * 读取yaml文件
   */
  ipcMain.handle("config.readYaml", async (_, file: string, keys?: (string | number)[]) => {
    try {
      if (!fs.existsSync(file)) return null;
      const content = await fsp.readFile(file, { encoding: "utf-8" });
      const yaml = await import("yaml");
      const config = yaml.parse(content);
      let result: any = config;
      if (keys) {
        for (const key of keys) {
          result = result[key];
        }
      }
      return result;
    } catch (e) {
      console.error("[config-file] read yaml file error", file, e);
      return null;
    }
  });

  /**
   * 读取简单的*.conf配置文件
   * 只有key=value格式的配置
   */
  ipcMain.handle("config.readSimpleConf", async (_, file: string, key?: string | string[]) => {
    try {
      if (!fs.existsSync(file)) return null;

      const config: Record<string, string> = {};
      await readFileAllLines(file, line => {
        line = line.trim();
        if (!line) return; // 空行
        const idx = line.indexOf("#");
        if (idx == 0) return; // 注释行
        if (idx > 0) line = line.substring(0, idx).trim();
        if (line.indexOf("=") < 0) return;
        const [k, v] = line.split("=");
        let value = v.trim();
        // 去掉字符串的引号
        if ((value.startsWith("'") && value.endsWith("'")) || (value.startsWith('"') && value.endsWith('"'))) {
          value = value.substring(1, value.length - 1);
        }
        config[k.trim()] = value;
      });

      let result: any = config;
      if (key) {
        if (Array.isArray(key)) {
          // 取多个key值, 返回一个对象
          result = {};
          for (const k of key) {
            result[k] = config[k];
          }
        } else {
          result = config[key];
        }
      }
      return result;
    } catch (e) {
      console.error("[config-file] read simple conf file error", file, e);
      return null;
    }
  });
})();
